<template>
  <div class="job-list">
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="job in jobs" :key="job.job_id">
          <td>{{ job.job_id }}</td>
          <td>{{ job.os }}</td>
          <td>{{ job.submit_time }}</td>
          <td>{{ job.queue_time }}</td>
          <td>{{ job.start_time }}</td>
          <td>{{ job.end_time }}</td>
          <td>{{ job.cpu }}</td>
          <td>{{ job.memory }}</td>
          <td>{{ job.status }}</td>
          <td><ProgressBar :progress="job.progress" /></td>
          <td>
            <button 
              v-if="shouldShowRun(job.status)" 
              @click="runJob(job.job_id)"
              class="action-btn run-btn"
            >
              运行
            </button>
            <button 
              v-if="shouldShowAbort(job.status)" 
              @click="abortJob(job.job_id)"
              class="action-btn abort-btn"
            >
              中止
            </button>
            <button 
              v-if="shouldShowTaskDetail(job.status)" 
              @click="showTaskDetails(job.job_id)"
              class="action-btn detail-btn"
            >
              Task详情
            </button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button 
        @click="prevPage" 
        :disabled="currentPage === 1"
        class="page-btn"
      >
        Previous
      </button>
      <span class="page-info">Page {{ currentPage }}</span>
      <button 
        @click="nextPage"
        class="page-btn"
      >
        Next
      </button>
    </div>
    <Toast 
      v-if="showToast" 
      :message="toastMessage" 
      @close="showToast = false" 
    />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getJobList, runJob, abortJob } from '../../api/jobs'
import ProgressBar from '../common/ProgressBar.vue'
import Toast from '../common/Toast.vue'

export default {
  components: { ProgressBar, Toast },
  props: {
    env_id: {
      type: String,
      required: true
    }
  },
  emits: ['show-task-details'],
  setup(props, { emit }) {
    const jobs = ref([])
    const currentPage = ref(1)
    const showToast = ref(false)
    const toastMessage = ref('')
    
    const headers = [
      'Job编号', '运行操作系统', '提交时间', '排队时间', 
      '开始时间', '结束时间', '占用cpu数量', '占用内存数量(GB)', 
      'status', '进度', '操作'
    ]

    const fetchJobs = async () => {
      try {
        const data = await getJobList(currentPage.value, props.env_id)
        jobs.value = data.jobs
      } catch (error) {
        console.error('Failed to fetch jobs:', error)
        showToastMessage('获取Job列表失败')
      }
    }

    onMounted(fetchJobs)

    const nextPage = () => {
      currentPage.value++
      fetchJobs()
    }

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--
        fetchJobs()
      }
    }

    const shouldShowTaskDetail = (status) => {
      return status !== 'waitting'
    }

    const shouldShowRun = (status) => {
      return status === 'waitting' || status === 'abort' || status === 'finish'
    }

    const shouldShowAbort = (status) => {
      return status === 'runing'
    }

    const showTaskDetails = (job_id) => {
      emit('show-task-details', job_id)
    }

    const showToastMessage = (message) => {
      toastMessage.value = message
      showToast.value = true
      setTimeout(() => {
        showToast.value = false
      }, 3000)
    }

    const runJobHandler = async (job_id) => {
      try {
        await runJob(job_id)
        showToastMessage('成功，已经进入排队等待调度')
      } catch (error) {
        console.error('Failed to run job:', error)
        showToastMessage('运行Job失败')
      }
    }

    const abortJobHandler = async (job_id) => {
      try {
        await abortJob(job_id)
        showToastMessage('成功，正在执行中止操作')
      } catch (error) {
        console.error('Failed to abort job:', error)
        showToastMessage('中止Job失败')
      }
    }

    return {
      jobs,
      headers,
      currentPage,
      showToast,
      toastMessage,
      nextPage,
      prevPage,
      shouldShowTaskDetail,
      shouldShowRun,
      shouldShowAbort,
      showTaskDetails,
      runJob: runJobHandler,
      abortJob: abortJobHandler
    }
  }
}
</script>

<style scoped>
.job-list {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  font-size: 14px;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

tr:hover {
  background-color: #f8f9fa;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  background-color: #f1f1f1;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

.action-btn {
  padding: 6px 12px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.detail-btn {
  background-color: #17a2b8;
  color: white;
}

.run-btn {
  background-color: #28a745;
  color: white;
}

.abort-btn {
  background-color: #dc3545;
  color: white;
}

.action-btn:hover {
  opacity: 0.8;
}
</style>